package com.liujunwen.demo.controller;

import com.liujunwen.demo.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class Consumer {
    private static final Logger log = LoggerFactory.getLogger(Consumer.class);

    @RabbitHandler
    @RabbitListener(queues = "queue1")
    public void receive(byte[] data) throws IOException {
        log.info("rabbitmq message handle...");
        final String info = new String(data, "utf-8");
        log.info("rabbitmq message is {}", info);
        WebSocketServer.sendInfo(info);
    }

    @RabbitListener(queues = "queue1")
    public void receive2(byte[] data) throws IOException {
        log.info("rabbitmq message handle22222...");
        final String info = new String(data, "utf-8");
        log.info("rabbitmq message222222 is {}", info);
        WebSocketServer.sendInfo(info);
    }


    //支持自动声明绑定，声明之后自动监听队列的队列，此时@RabbitListener注解的queue和bindings不能同时指定，否则报错
    @RabbitListener(bindings = {@QueueBinding(value = @Queue(value = "autorCreateQ", durable = "true"),
            exchange = @Exchange(value = "autorCreateExchange", durable = "true"), key = "autorCreateRouteKey")})
    public void handleMessage(Message message) {
        System.out.println("====消费消息" + message.getMessageProperties().getConsumerQueue() + "===handleMessage");
        System.out.println(message.getMessageProperties());
        System.out.println(new String(message.getBody()));
    }
}


